package com.lzb.compressmaster.fragment;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.StatFs;
import android.provider.Settings;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresPermission;
import androidx.fragment.app.Fragment;

import com.blankj.utilcode.util.AppUtils;
import com.lzb.compressmaster.BaseApplication;
import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.Utils;
import com.blankj.utilcode.util.UtilsTransActivity;
import com.lzb.compressmaster.BaseNoModelFragment;
import com.lzb.compressmaster.Content;
import com.lzb.compressmaster.R;
import com.lzb.compressmaster.activity.AddPictureActivity;
import com.lzb.compressmaster.activity.CompressPackageActivity;
import com.lzb.compressmaster.activity.GoCompressActivity;
import com.lzb.compressmaster.activity.InputPwdActivity;
import com.lzb.compressmaster.activity.PhoneStorageActivity;
import com.lzb.compressmaster.activity.PictureCompressFileActivity;
import com.lzb.compressmaster.activity.PrivacyFileActivity;
import com.lzb.compressmaster.activity.RecentFileActivity;
import com.lzb.compressmaster.activity.SelAudioActivity;
import com.lzb.compressmaster.activity.SelDocumentActivity;
import com.lzb.compressmaster.activity.SelPictureActivity;
import com.lzb.compressmaster.activity.SelVideoActivity;
import com.lzb.compressmaster.activity.SetPwdActivity;
import com.lzb.compressmaster.activity.VideoCompressFileActivity;
import com.lzb.compressmaster.basic.utils.SPUtil;
import com.lzb.compressmaster.databinding.FragmentHomeBinding;
import com.lzb.compressmaster.dialog.PermissionExplainDialog;
import com.lzb.compressmaster.dialog.ReqPermissionDialog;
import com.lzb.compressmaster.utils.StorageUtil;

import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link HomeFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class HomeFragment extends BaseNoModelFragment<FragmentHomeBinding> implements View.OnClickListener {

    private boolean isFirst = true;

    @Override
    protected int onCreate() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initView() {
        mDataBinding.tvPhoneStorage.setOnClickListener(this);
        mDataBinding.tvRecentFile.setOnClickListener(this);
        mDataBinding.llGoCompress.setOnClickListener(this);
        mDataBinding.llPictureCompress.setOnClickListener(this);
        mDataBinding.llVideoCompress.setOnClickListener(this);
        mDataBinding.tvCompressPackage.setOnClickListener(this);
        mDataBinding.tvImage.setOnClickListener(this);
        mDataBinding.tvAudio.setOnClickListener(this);
        mDataBinding.tvDocument.setOnClickListener(this);
        mDataBinding.tvVideo.setOnClickListener(this);
        mDataBinding.llSizeCompress.setOnClickListener(this);
        mDataBinding.llInfoErasure.setOnClickListener(this);
        mDataBinding.llImg2Pdf.setOnClickListener(this);
        mDataBinding.llFormatConvert.setOnClickListener(this);
        mDataBinding.llImageSplice.setOnClickListener(this);
        mDataBinding.llFileEncryption.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tvPhoneStorage) {//手机储存
            getPermission(PhoneStorageActivity.class);
        } else if (id == R.id.tvRecentFile) {//最近文件
            getPermission(RecentFileActivity.class);
        } else if (id == R.id.llGoCompress) {//去压缩
            getPermission(GoCompressActivity.class);
        } else if (id == R.id.llPictureCompress) {//图片压缩
            startActivity(PictureCompressFileActivity.class);
        } else if (id == R.id.llVideoCompress) {//视频压缩
            startActivity(VideoCompressFileActivity.class);
        } else if (id == R.id.tvCompressPackage) {//压缩包
            getPermission(CompressPackageActivity.class);
        } else if (id == R.id.tvImage) {//图片
            startActivity(SelPictureActivity.class);
        } else if (id == R.id.tvAudio) {//音频
            startActivity(SelAudioActivity.class);
        } else if (id == R.id.tvDocument) {//文档
            getPermission(SelDocumentActivity.class);
        } else if (id == R.id.tvVideo) {//视频
            startActivity(SelVideoActivity.class);
        } else if (id == R.id.llSizeCompress) {//照片尺寸压缩
            AddPictureActivity.type = 1;
            startActivity(AddPictureActivity.class);
        } else if (id == R.id.llInfoErasure) {//照片信息抹除
            AddPictureActivity.type = 2;
            startActivity(AddPictureActivity.class);
        } else if (id == R.id.llImg2Pdf) {//图片转pdf
            AddPictureActivity.type = 3;
            startActivity(AddPictureActivity.class);
        } else if (id == R.id.llFormatConvert) {//格式转换
            AddPictureActivity.type = 4;
            startActivity(AddPictureActivity.class);
        } else if (id == R.id.llImageSplice) {//图片拼接
            AddPictureActivity.type = 5;
            startActivity(AddPictureActivity.class);
        } else if (id == R.id.llFileEncryption) {//文件加密
            boolean isHave = SPUtil.getBoolean(mContext, Content.isHavePassword, false);
            boolean isNeed = SPUtil.getBoolean(mContext, Content.isNeedPassword, true);
            if (isHave) {
                if (isFirst || isNeed) {
                    isFirst = false;
                    startActivity(InputPwdActivity.class);
                } else {
                    startActivity(PrivacyFileActivity.class);
                }
            } else {
                startActivity(SetPwdActivity.class);
            }
        }
    }

    @Override
    protected void initData() {
        StatFs statFs = StorageUtil.getInternalMemory();//内部存储
        //已使用
        long usedLong = statFs.getTotalBytes() - statFs.getAvailableBytes();
        //总内存
        long allLong = statFs.getTotalBytes();
        //已用百分比
        int progress = Math.round((statFs.getTotalBytes() - statFs.getAvailableBytes()) * 100f / statFs.getTotalBytes());
        mDataBinding.tvPhoneMemorise.setText(getString(R.string.available) + ConvertUtils.byte2FitMemorySize((allLong - usedLong), 2) + "/" + getString(R.string.total) + ConvertUtils.byte2FitMemorySize(allLong, 2));
        mDataBinding.sbPhoneProgress.setProgress(progress);
        mDataBinding.sbPhoneProgress.setProgress(progress);
    }

    private void getPermission(Class cls) {
        PermissionExplainDialog dialog = new PermissionExplainDialog(mContext);
        dialog.setContent(getString(R.string.get_all_storage_permission));
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (Environment.isExternalStorageManager()) {
                startActivity(cls);
                return;
            }
            ReqPermissionDialog reqPermissionDialog = new ReqPermissionDialog(mContext);
            reqPermissionDialog.setListener(new ReqPermissionDialog.Ilistener() {
                @Override
                public void clickConfirm() {
                    requestManageExternalStoragePermission(getActivity());
                }
            });
            reqPermissionDialog.show();
        } else {
            PermissionUtils.permission(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE).explain(new PermissionUtils.OnExplainListener() {
                @Override
                public void explain(@NonNull UtilsTransActivity activity, @NonNull List<String> denied, @NonNull ShouldRequest shouldRequest) {
//                if (PermissionUtils.isGranted(Manifest.permission.MANAGE_EXTERNAL_STORAGE)) {
//                    shouldRequest.start(false);
//                } else {
                    dialog.show();
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            shouldRequest.start(true);
                        }
                    }, 500);
//                }
                }
            }).callback(new PermissionUtils.SimpleCallback() {
                @Override
                public void onGranted() {
                    dialog.dismiss();
                    startActivity(cls);
                }

                @Override
                public void onDenied() {
                    dialog.dismiss();
                    try {
                        // 设置跳过下次启动页跳转，因为从应用详情页面返回时不应该跳转到启动页
                        BaseApplication.setSkipSplashOnNextStart(true);
                        AppUtils.launchAppDetailsSettings();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).request();
        }
    }

    @RequiresPermission(value = Manifest.permission.MANAGE_EXTERNAL_STORAGE)
    private void requestManageExternalStoragePermission(@NonNull Activity activity) {
        try {
            // 设置跳过下次启动页跳转，因为从系统权限页面返回时不应该跳转到启动页
            BaseApplication.setSkipSplashOnNextStart(true);
            Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
            Uri uri = Uri.fromParts("package", Utils.getApp().getPackageName(), null);
            intent.setData(uri);
            activity.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}